﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using LuckyBingoRcon.Commands.Events;

namespace LuckyBingoRcon.Commands
{
	public class DvardumpCommand : Command
	{
		public EventHandler<ServerVarsCommandEventArgs> OnResponse;

		public DvardumpCommand(bool setCommand)
		{
			if(!setCommand)
                base.commandText = "dvardump";
            else
                base.commandText = "setadmindvar ";
            base.args = null;
		}

		protected override void CommandOnResponse(string response)
		{
			Dictionary<string, string> vars = new Dictionary<string, string>();
			StringReader sr = new StringReader(response);

            try
            {
				while (sr.Peek() > -1)
                    {
                        string line = sr.ReadLine().Trim();
                        int firstQuote = line.IndexOf('"');
                        int lastQuote = line.LastIndexOf('"');
                        if (firstQuote > -1 && lastQuote > -1 && !firstQuote.Equals(lastQuote))         // Added the last piece because max rate seems buggy and doesn't completely get received sometimes
                        {
                            string variable = line.Substring(0, firstQuote).Trim();
                            string value = line.Substring(firstQuote + 1, lastQuote - firstQuote - 1).Trim();
                            vars.Add(variable, value);
                        }
                    }

                    if (OnResponse != null)
                    {
                        ServerVarsCommandEventArgs e = new ServerVarsCommandEventArgs();
                        e.ServerVariables = vars;
                        e.RawResponse = response;
                        OnResponse(this, e);
                    }
            }
            catch (Exception error)
            {
                if (OnResponse != null)
                {
                    ServerVarsCommandEventArgs e = new ServerVarsCommandEventArgs();
                    e.ServerVariables = vars;
                    e.Error = error;
                    e.RawResponse = response;
                    OnResponse(this, e);
                }
            }

			sr.Close();
		}

        public override string ToString()
        {
            if (base.commandText.Contains("setadmindvar"))   // Is a set command
                return "Set\t" + base.args[0] + "\t=\t" + base.args[1];
            else
                return "Get\tServer Variables";
        }
	}
}
